﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MVVM.Core;
using Microsoft.Office.Interop.Excel;

namespace ObjectModel.Excel.Old
{
    /// <summary>
    /// A class that allows the linking of two OfflineRange object.
    /// </summary>
    public class LinkedRange : LinkedRangeBase
    {
		public override Old.ConditionalOfflineRange SourceRange
		{
			get { return base.SourceRange; }
			set
			{
				base.SourceRange = value;
				SourceRange.PropertyChanged += SourceRange_PropertyChanged;
			}
		}

    	public string Title { get { return "test title"; }
    		set {}
    	}

		public bool Checked { get { return true; }
    		set {}
    	}
		
		// Parameterless constructor for serialization
        public LinkedRange() { }

    	public LinkedRange(Range range) : this()
        {
            TargetRange = new Old.ObservableRange(range) { Application = range.Application};
			
        }

        private void SourceRange_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            UpdateValues();
        }

        public void UpdateValues()
        {
            if (TargetRange != null && SourceRange != null)
            {
                bool transposed = false;
            	bool truncate = false;
				bool resize = false;
            	Range sourceRange = SourceRange.Range;
            	Range targetRange = TargetRange.Range;
				switch (targetRange.CompareDimensions(sourceRange))
				{
				    case RangeExtensions.DimensionEquality.Equal:
				        break;

				    case RangeExtensions.DimensionEquality.Transposed:
				        transposed = true;
				        break;

				    case RangeExtensions.DimensionEquality.NotEqual:
						// Get required action from target cell
						if(TargetRange.ResizeAction == Old.ResizeActions.Truncate) {
							truncate = true;
						}
						else if(TargetRange.ResizeAction == Old.ResizeActions.Expand) {
							resize = true;
						}
						else if (TargetRange.ResizeAction == Old.ResizeActions.Error) {
							throw new InvalidOperationException("Source range does not have same dimensions as target range.");	
						}
						break;
				}

				if(truncate) {
					TargetRange.Range.Value = SourceRange.GetValue(false, (int)TargetRange.Range.Height, (int)TargetRange.Range.Width);
				}
				else if(resize) {
					// Resize target range
					TargetRange.Range = targetRange.Worksheet.Range[targetRange.Worksheet.Cells[targetRange.Row, targetRange.Column]
						, targetRange.Worksheet.Cells[targetRange.Row + sourceRange.Rows.Count -1, targetRange.Column + sourceRange.Columns.Count -1]];
					
					TargetRange.Range.Value = 	SourceRange.GetValue(false);

				}
				else
				{
				 TargetRange.Range.Value = 	SourceRange.GetValue(transposed);
				}
            }
        }
    }
}
